package StudyCode.summary.mycollection;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ReturnsTheGivenIteratorSingleElement {
	public static <T> T single(Iterator<T> iterator) {
		return assertNotNull(iterator, singleOrNull(iterator));
	}


	public static <T> T single(Iterable<T> iterable) {
		return single(iterable.iterator());
	}

	private static <T> T assertNotNull(Iterator<T> iterator, T result) {

		return result;
	}


	public static <T> T singleOrNull(Iterator<T> iterator) {
		T result = iterator.hasNext() ? iterator.next() : null;
		if (iterator.hasNext()) {
			throw new NoSuchElementException("More than one element in "
					+ iterator + ". First element is '" + result
					+ "' and the second element is '" + iterator.next()
					+ "'");
		}
		return result;
	}


	public static <T> T singleOrNull(Iterable<T> iterable) {
		return singleOrNull(iterable.iterator());
	}
}
